/**
 * 自定义hooks之-在useEffect中使用异步
 */
import { DependencyList, useEffect } from "react";

type Effect = () => Promise<void>;

function useAsyncEffect(effect: Effect, deps?: DependencyList) {
  useEffect(() => {
    let cancelled = false;

    async function runEffect() {
      try {
        await effect();
      } catch (error) {
        console.error(error);
      }
    }

    if (cancelled === false) {
      runEffect();
    }

    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);
}

export default useAsyncEffect;
